import React, { useState } from 'react'
import { Button, Input, Card, Space, Typography } from 'antd'
import { toastManager } from '../components/Toast'
import { getDictByKey, postUpdateDictBykey, postAddDict } from '../api'
import { hasLogin } from '../utils/cookie'

const { Title, Text } = Typography

const DictPage: React.FC = () => {
  const [key, setKey] = useState('')
  const [description, setDescription] = useState('')
  const [currentValue, setCurrentValue] = useState<any>(null)
  const [newValue, setNewValue] = useState('')
  const [loading, setLoading] = useState(false)

  // 检查用户权限
  const checkPermission = () => {
    if (!hasLogin()) {
      toastManager.warning('请先登录后再进行操作')
      return false
    }
    return true
  }

  // 查询字典值
  const handleQuery = async () => {
    if (!checkPermission()) return

    if (!key.trim()) {
      toastManager.warning('请输入Key')
      return
    }

    setLoading(true)
    try {
      const res: any = await getDictByKey(key)
      if (res?.data?.value) {
        setCurrentValue(res.data.value)
        setNewValue(JSON.stringify(res.data.value, null, 2))
        toastManager.success('查询成功')
      } else {
        setCurrentValue(null)
        setNewValue('')
        toastManager.info('未找到对应的数据')
      }
    } catch (error) {
      console.error('查询失败:', error)
      toastManager.error('查询失败')
    } finally {
      setLoading(false)
    }
  }

  // 更新字典值
  const handleUpdate = async () => {
    if (!checkPermission()) return

    if (!key.trim()) {
      toastManager.warning('请输入Key')
      return
    }

    if (!newValue.trim()) {
      toastManager.warning('请输入要更新的值')
      return
    }

    let parsedValue
    try {
      parsedValue = JSON.parse(newValue)
    } catch (error) {
      toastManager.error('请输入有效的JSON格式')
      return
    }

    setLoading(true)
    try {
      const res: any = await postUpdateDictBykey(key, parsedValue)
      const msg = res?.message || '更新成功'
      toastManager.success(msg)
    } catch (error: any) {
      console.error('更新失败:', error)
      const msg = error?.response?.data?.message || '更新失败'
      toastManager.error(msg)
    } finally {
      setLoading(false)
    }
  }

  // 新增字典
  const handleAdd = async () => {
    if (!checkPermission()) return

    if (!key.trim()) {
      toastManager.warning('请输入Key')
      return
    }

    if (!newValue.trim()) {
      toastManager.warning('请输入要新增的值')
      return
    }

    let parsedValue
    try {
      parsedValue = JSON.parse(newValue)
    } catch (error) {
      toastManager.error('请输入有效的JSON格式')
      return
    }

    setLoading(true)
    try {
      const res: any = await postAddDict(key, parsedValue, description)
      const msg = res?.message || '新增成功'
      toastManager.success(msg)
    } catch (error: any) {
      console.error('新增失败:', error)
      const msg = error?.response?.data?.message || '新增失败'
      toastManager.error(msg)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="p-6">
      <Title level={2}>字典</Title>

      <Card className="mb-6">
        <Space direction="vertical" size="large" className="w-full">
          <div>
            <Text strong>Key:</Text>
            <Input
              placeholder="请输入字典Key"
              value={key}
              onChange={(e) => setKey(e.target.value)}
              className="mt-2"
            />
          </div>

          <div>
            <Text strong>描述:</Text>
            <Input
              placeholder="请输入字典描述"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="mt-2"
            />
          </div>

          <Space>
            <Button type="primary" onClick={handleQuery} loading={loading}>
              查询
            </Button>
          </Space>
        </Space>
      </Card>

      {currentValue && (
        <Card title="当前值" className="mb-6">
          <pre className="bg-gray-100 p-4 rounded overflow-x-auto">
            {JSON.stringify(currentValue, null, 2)}
          </pre>
        </Card>
      )}

      <Card title="修改值">
        <Space direction="vertical" size="large" className="w-full">
          <div>
            <Text strong>新值 (JSON格式):</Text>
            <Input.TextArea
              placeholder='请输入JSON格式的值，例如: {"isShow": true}'
              value={newValue}
              onChange={(e) => setNewValue(e.target.value)}
              rows={6}
              className="mt-2 font-mono"
            />
          </div>

          <Space>
            <Button type="primary" onClick={handleUpdate} loading={loading}>
              更新
            </Button>
            <Button onClick={handleAdd} loading={loading}>
              新增
            </Button>
          </Space>
        </Space>
      </Card>
    </div>
  )
}

export default DictPage